package com.teamb6.shop.config;

import com.teamb6.shop.domain.Admin;
import com.teamb6.shop.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AdminDetailsService implements UserDetailsService {
    private final AdminService adminService;

    @Autowired
    AdminDetailsService(AdminService adminService){
        this.adminService = adminService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("-------------------------------------------------");
        System.out.println(username);
        Admin admin = adminService.selectAdmin(username);
        if(admin == null){
            throw new UsernameNotFoundException("用户不存在！");
        }
        List<SimpleGrantedAuthority> simpleGrantedAuthorities = new ArrayList<>();
        simpleGrantedAuthorities.add(new SimpleGrantedAuthority("ADMIN"));
        System.out.println(new org.springframework.security.core.userdetails.User(admin.getAdminname(),admin.getPassword(),simpleGrantedAuthorities));
        return new org.springframework.security.core.userdetails.User(admin.getAdminname(),admin.getPassword(),simpleGrantedAuthorities);
    }
}
